package com.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.SerializationUtils;
import com.example.address_api.AddressClient;
import com.example.address_model.entity.AddressBook;
import com.example.common.Result;
import com.example.config.JwtConfig;
import com.example.dish_api.DishClient;
import com.example.dish_model.entity.Dish;
import com.example.exceptions.BusinessException;
import com.example.exceptions.enumetation.ResponseEnum;
import com.example.order.entity.OrderDetail;
import com.example.order.entity.Orders;
import com.example.order.mapper.OrdersMapper;
import com.example.order.service.OrderDetailService;
import com.example.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shopping_cart_api.ShoppingCartClient;
import com.example.shopping_cart_model.entity.ShoppingCart;
import com.example.user_api.UserClient;
import com.example.user_model.entity.User;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author sjz
 * @since 2024-07-08
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrderService {
    @Resource
    private ShoppingCartClient shoppingCartClient;

    @Resource
    private UserClient userClient;

    @Resource
    private AddressClient addressClient;

    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private DishClient dishClient;

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 用户下单
     *
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {
        //获取当前用户id
        String currentId = this.getId();
        //查询当前购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        Result<List<ShoppingCart>> list = shoppingCartClient.list();
        List<ShoppingCart> cartList = list.getData();

        if (cartList == null || cartList.size() == 0) {
            throw new BusinessException(ResponseEnum.SHOPPINGCART_IS_EMPTY);
        }

        //查询用户数据
        User user = userClient.getById(currentId);

        //查询地址数据
        String addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressClient.getById(addressBookId);

        if (addressBookId == null) {
            throw new BusinessException(ResponseEnum.ADDRESS_ERROR);
        }

        //myBatisPlus提供的工具类IdWorker,生成一个订单编号
        String orderNumber = IdWorker.getIdStr();//订单号

        //原子操作,线程安全(计算订单总金额)
        AtomicInteger amount = new AtomicInteger(0);


        //给订单明细赋值
        List<OrderDetail> orderDetails = cartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderNumber);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            //累加amount
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        //给订单信息赋值
        orders.setId(orderNumber);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(currentId);
        orders.setNumber(String.valueOf(orderNumber));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //将数据插入到订单表,单条数据
        this.save(orders);

        //将数据插入到订单明细表,多条数据
        orderDetailService.saveBatch(orderDetails);
        //下单完成后,清空购物车数据
        shoppingCartClient.clean();

    }

    @Override
    public void again(Orders orders) {
        //String token = (String) redisTemplate.opsForValue().get("Authorization");
        String userId = this.getId();
        //清空购物车
        shoppingCartClient.clean();
        //根据订单号查询订单对应的菜品详情
        String orderId = orders.getId();
        log.info("再次下单订单号为:{}的菜品",orderId);
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetails = orderDetailService.list(wrapper);
        orderDetails.forEach(item->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            shoppingCart.setName(item.getName());
            shoppingCart.setDishId(item.getDishId());
            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCartClient.add(shoppingCart);
        });


        List<String> list = new ArrayList<>();
        //构建查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, list);
        //查询菜品表,获取该订单的所有菜品
        List<Dish> dishes = dishClient.list(queryWrapper);



    }


    /**
     * 利用请求头中的手机号,获取用户id,给其他方法调用
     *
     * @return
     */
    public String getId() {
        //获取请求头中的token
        String token = request.getHeader("Authorization").replace("\"", "");
        log.info("token:{}", token);
        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        //根据手机号查询当前用户
        String phone = claims.get("name", String.class);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userClient.getOne(wrapper);
        //获取id
        return user.getId();
    }
}
